package org.example.uhy.domain.model.upgrade.execution.node;

import org.example.uhy.domain.model.upgrade.execution.UpgradeExecutionContext;
import org.example.uhy.domain.model.upgrade.schema.LogicalOperator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class LogicalExecutionNode implements UpgradeExecutionNode {
    private List<UpgradeExecutionNode> children = new ArrayList<>();
    private LogicalOperator operator;

    public LogicalExecutionNode(LogicalOperator operator) {
        this.operator = operator;
    }

    public void setOperator(LogicalOperator operator) {
        this.operator = operator;
    }

    public void addChild(UpgradeExecutionNode child) {
        children.add(child);
    }

    @Override
    public boolean match(UpgradeExecutionContext context) {
        if (operator == LogicalOperator.AND) {
            boolean result = true;
            for (UpgradeExecutionNode child : children) {
                if (!child.match(context)) {
                    result = false;
                    break;
                }
            }
            return result;
        } else {
            boolean result = false;
            for (UpgradeExecutionNode child : children) {
                if (child.match(context)) {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }

    public Iterator<UpgradeExecutionNode> iterator() {
        return children.iterator();
    }

    @Override
    public String toString() {
        return operator.name();
    }
}